package com.glela.api.pay.util;

import java.io.InputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 
 * @name xml报文处理
 */
public class PaymentUtil {
	
	/**
	 * xml报文转换为 map
	 * @param xml
	 * @return
	 */
	public static Map<String, Object> getWeChatNodityByXml(String xml) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Document doc = read(xml);
			Element e = getRootElement(doc);
			treeWalk(e, map);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * io流转换为map  微信回调使用
	 * @param in  io流
	 * @return
	 */
	public static Map<String, Object> getWeChatNodityByXml(InputStream in) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Document doc = read(in);
			Element e = getRootElement(doc);
			treeWalk(e, map);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return map;
	}

	public static Document read(String xml) throws MalformedURLException, DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new StringReader(xml));
		return document;
	}

	public static Document read(InputStream in) throws MalformedURLException, DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(in);
		return document;
	}

	public static Element getRootElement(Document doc) {
		return doc.getRootElement();
	}

	@SuppressWarnings("rawtypes")
	public static void treeWalk(Element root, Map<String, Object> map) {
		for (Iterator ie = root.elementIterator(); ie.hasNext();) {
			Element element = (Element) ie.next();
			map.put(element.getName(), element.getStringValue());
			/**
			 * // 枚举属性 for (Iterator ia = element.attributeIterator();
			 * ia.hasNext();) { Attribute attribute = (Attribute) ia.next();
			 * System.out.println(attribute.getName() + ":" +
			 * attribute.getData()); } // 枚举当前节点下所有子节点 for (Iterator ieson =
			 * element.elementIterator(); ieson.hasNext();) { Element elementSon
			 * = (Element) ieson.next(); System.out.println(elementSon.getName()
			 * + ":" + elementSon.getText()); }
			 **/
		}
	}
}
